package com.supermarket.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.supermarket.service.ValidateCodeService;
import com.supermarket.vo.ValidateCodeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.supermarket.constant.RedisConstant.LOGIN_VALIDATE_CODE_PREFIX;

@Service
@RequiredArgsConstructor
public class ValidateCodeServiceImpl implements ValidateCodeService {

    private final StringRedisTemplate redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {

        // 使用hutool工具包中的工具类生成图片验证码
        //参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);

        // 获取验证码
        String codeValue = circleCaptcha.getCode();
        // 获取验证码图片
        String imageBase64 = circleCaptcha.getImageBase64();

        // 生成uuid
        String codeKey = UUID.randomUUID().toString().replace("-", "");

        // 存入redis
        redisTemplate.opsForValue().set(LOGIN_VALIDATE_CODE_PREFIX + codeKey,codeValue,5, TimeUnit.MINUTES);

        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKey);
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);

        return validateCodeVo;
    }
}
